<template>
    <div id="app">
        <the-header></the-header>
        <transition name="el-zoom-in-center">
            <keep-alive>
                <router-view
                        :hotDrugs="hotDrugs"
                        :drugs="drugs"
                        :searchDrugs="searchDrugs"
                        @search="search"
                        @addCount="addCount"
                ></router-view>
            </keep-alive>
        </transition>
        <shop-cart :drugs="selectedDrugs" ref="shopcart"></shop-cart>
    </div>
</template>

<script type="text/ecmascript-6">
    import TheHeader from "@/components/client/TheHeader/TheHeader";
    import ShopCart from "@/components/client/ShopCart/ShopCart";

    export default {
        data() {
            return {
                hotDrugs: [],
                drugs: {},
                searchDrugs: []
            }
        },
        components: {
            TheHeader,
            ShopCart
        },
        created() {
            this.$http.get("/api/hotDrugs").then((response) => {
                this.hotDrugs = response.data.data;
            })
        },
        computed: {
            selectedDrugs() {
                let drugList = [];
                for (let type in this.drugs) {
                    for (let page in this.drugs[type]) {
                        this.drugs[type][page].forEach((drug) => {
                            if (drug.count && drug.count > 0) {
                                drugList.push(drug);
                            }
                        })
                    }
                }
                this.searchDrugs.forEach((drug) => {
                    if (drug.count && drug.count > 0) {
                        drugList.push(drug);
                    }
                });
                return drugList;
            }
        },
        methods: {
            search(searchName) {
                this.$http.get("/api/search", {
                    params: {
                        "searchName": searchName
                    }
                }).then((response) => {
                    this.searchDrugs = response.data.data;
                })
            },
            addCount(x, y) {
                this.$refs["shopcart"].drop(x, y)
            }
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus">
    @import "../../assets/stylus/base.styl";
</style>
